# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import datetime
import pytz
from coin.exchange.base.kr_rest.level_book import (LevelBook, LevelElement)
from coin.exchange.base.kr_rest.public_client_base import PublicClientBase
from coin.exchange.bittrex_v1.kr_rest.native_public_client import BittrexNativePublicClient
from coin.proto.coin_market_query_pb2 import ProductTicker


class BittrexFeedParser(object):
  @staticmethod
  def parse_native_ticker(update_msg: dict, product):
    norm_ticker = ProductTicker()
    norm_ticker.high = float(update_msg['High'])
    norm_ticker.low = float(update_msg['Low'])
    norm_ticker.last = float(update_msg['Last'])
    norm_ticker.ask = float(update_msg['Ask'])
    norm_ticker.bid = float(update_msg['Bid'])
    exchange_time = datetime.datetime.strptime(update_msg['TimeStamp'], "%Y-%m-%dT%H:%M:%S.%f")
    exchange_time = pytz.utc.localize(exchange_time)
    norm_ticker.exchange_timestamp = int(exchange_time.timestamp() * (10**9))
    norm_ticker.volume_24hr = float(update_msg['Volume'])
    norm_ticker.native_symbol = product.native_symbol
    norm_ticker.symbol = product.symbol
    return norm_ticker

  @staticmethod
  def parse_level_book(update_msg, product):
    level_book = LevelBook(product)
    for elem in update_msg['result']['sell']:
      level_elem = LevelElement(float(elem['Rate']), float(elem['Quantity']), None)
      level_book.add_ask(level_elem)
    for elem in update_msg['result']['buy']:
      level_elem = LevelElement(float(elem['Rate']), float(elem['Quantity']), None)
      level_book.add_bid(level_elem)
    level_book.finalize()
    return level_book


class BittrexPublicClient(PublicClientBase):
  def __init__(self):
    self.native_client = BittrexNativePublicClient()

  def query_ticker_impl(self, product):
    symbol = product.native_symbol
    update = self.native_client.query_detailed_ticker(symbol)
    update.msg = BittrexFeedParser.parse_native_ticker(update.msg, product)
    return update

  def query_level_book_impl(self, product):
    symbol = product.native_symbol
    update = self.native_client.query_getorderbook(symbol)
    update.msg = BittrexFeedParser.parse_level_book(update.msg, product)
    return update
